//
//  ViewController.m
//  FFMpegKitDemo
//
//  Created by ilongge on 2023/7/13.
//


#import "ViewController.h"
#import "XLPlayerViewController.h"
#import "AudioDecodeViewController.h"
#import "AudioResampleViewController.h"
#import "AudioEncodeViewController.h"
#import "VideoDecodeViewController.h"
#import "VideoEncodeViewController.h"

#import <TZImagePickerController.h>
#import <ffmpegkit/ffmpegkit.h>

@interface ViewController ()
<
TZImagePickerControllerDelegate
>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"示例";
}

/// 音频解码
- (IBAction)audioDecodeAction:(id)sender { 
    AudioDecodeViewController *decodeVC = [[AudioDecodeViewController alloc] initWithNibName:@"AudioDecodeViewController" bundle:nil];
    [self.navigationController pushViewController:decodeVC animated:YES];
}
/// 音频编码
- (IBAction)audioEncodeAction:(id)sender {
    AudioEncodeViewController *EncodeVC = [[AudioEncodeViewController alloc] initWithNibName:@"AudioEncodeViewController" bundle:nil];
    [self.navigationController pushViewController:EncodeVC animated:YES];
}
/// 视频解码
- (IBAction)videoDecodeAction:(id)sender {
    VideoDecodeViewController *decodeVC = [[VideoDecodeViewController alloc] initWithNibName:@"VideoDecodeViewController" bundle:nil];
    [self.navigationController pushViewController:decodeVC animated:YES];
}
/// 视频编码
- (IBAction)videoEncodeAction:(id)sender {
    VideoEncodeViewController *encodeVC = [[VideoEncodeViewController alloc] initWithNibName:@"VideoEncodeViewController" bundle:nil];
    [self.navigationController pushViewController:encodeVC animated:YES];
}
/// 音频重采样
- (IBAction)audioResampleAction:(id)sender {
    AudioResampleViewController *resample = [[AudioResampleViewController alloc] initWithNibName:@"AudioResampleViewController" bundle:nil];
    [self.navigationController pushViewController:resample animated:YES];
}
/// 播放器
- (IBAction)XLPlayerAction:(id)sender {
    XLPlayerViewController *playerVC = [[XLPlayerViewController alloc] initWithNibName:@"XLPlayerViewController" bundle:nil];
    [self.navigationController pushViewController:playerVC animated:YES];
}

/// 提取系统相册视频
- (IBAction)extractSystemAlbumVideo:(id)sender {
    //MaxImagesCount  可以选着的最大条目数
    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:2 delegate:self];
    
    // 是否显示可选原图按钮
    imagePicker.allowPickingOriginalPhoto = NO;
    // 是否允许显示视频
    imagePicker.allowPickingVideo = YES;
    // 是否允许显示图片
    imagePicker.allowPickingImage = NO;
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    // 这是一个navigation 只能present
    [self presentViewController:imagePicker animated:YES completion:nil];
}
/// 选择视频的回调
-(void)imagePickerController:(TZImagePickerController *)picker
       didFinishPickingVideo:(UIImage *)coverImage
                sourceAssets:(PHAsset *)asset
{
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    options.version = PHVideoRequestOptionsVersionOriginal;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    PHImageManager *manager = [PHImageManager defaultManager];
    [manager requestAVAssetForVideo:asset
                            options:options
                      resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        AVURLAsset *urlAsset = (AVURLAsset *)asset;
        NSURL *url = urlAsset.URL;
        [self ffmpegConvert:url];
    }];
}

- (void)ffmpegConvert:(NSURL *)videoUrl {
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    long long timeStart = [NSDate date].timeIntervalSince1970*1000;
    NSString *fileName = [NSString stringWithFormat:@"encode_video_%lld.mp4", timeStart];
    NSString *filePath = [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(), fileName];
    NSString *ffmpegCommand = [NSString stringWithFormat:@" -hwaccel videotoolbox -i %@ -b 3000k -c:v hevc_videotoolbox %@", videoUrl.path, filePath];
    printf("%s\n", ffmpegCommand.UTF8String);
    [FFmpegKit executeAsync:ffmpegCommand
       withCompleteCallback:^(FFmpegSession *session) {
        SessionState state = [session getState];
        ReturnCode* returnCode = [session getReturnCode];
        printf("FFmpeg process exited with state %s and code %d", [FFmpegKitConfig sessionStateToString:state].UTF8String, returnCode.getValue);
        dispatch_semaphore_signal(semaphore);
    } withLogCallback:^(Log *log) {
        printf("%s", log.getMessage.UTF8String);
    } withStatisticsCallback:^(Statistics *statistics) {
        
    }];
    // 等待信号量
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    long long timeStop = [NSDate date].timeIntervalSince1970*1000;
    printf("------------------- 转码耗时：%lld S\n", (timeStop - timeStart)/1000);
}

@end
